package com.xfz.Controller;

import com.xfz.common.Res;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;

import java.util.Iterator;

@RestController
@RequestMapping("/api/file")
public class FileController<JSONObject> {

    @PostMapping("/upload")
    public Res upload(MultipartFile file) {
        System.out.println(file.getOriginalFilename());
        try {
            String md5 = DigestUtils.md5DigestAsHex(file.getBytes());
            String fileName = md5
                    + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
            if (new File("D://upload/" + fileName).exists()) {
                return new Res(1, "上传成功", "http://localhost:9876/" + fileName);
            }
            file.transferTo(new File("D://upload/" + fileName));
            return new Res(1, "上传成功", "http://localhost:9876/" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Res(0, "上传失败");
        }
    }

    @PostMapping("/upload/list")
    public Res upload(MultipartHttpServletRequest request) {
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            MultipartFile file = request.getFile(fileNames.next());
            try {
                file.transferTo(new File("D:/upload/" + file.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new Res(1, "批量上传成功");
    }
}
